package com.guoranhao.tool.utils;

import com.aspose.pdf.*;
import com.aspose.pdf.devices.JpegDevice;
import com.aspose.pdf.devices.PngDevice;
import com.aspose.pdf.devices.Resolution;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class PdfUtils {

    /**
     * Description:  转换html到pdf(暂不支持)<br/>
     * Version V1.0  2020-3-31 15:54  by 秦涛   (qintao@cloud-young.com) 创建
     *
     * @param url          网址
     * @param outputStream 输出
     * @throws Exception
     */
    public static void convertHTMLFileToPDF(String url, OutputStream outputStream) throws Exception {
        // Specify the The base path/url for the html file which serves as images database
        String s = HttpUtils.requestGet(url, null, null);
        InputStream inputStream = new ByteArrayInputStream(
                s.getBytes("UTF-8"));
        HtmlLoadOptions htmloptions = new HtmlLoadOptions();
        // Load HTML file
        Document doc = new Document(inputStream, htmloptions);
        // Save HTML file
        doc.save(outputStream);
    }

    /**
     * Description:  转换pdf到word(doc)<br/>
     * Version V1.0  2020-3-31 15:58  by 秦涛   (qintao@cloud-young.com) 创建
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public static void convertPDFToDoc(InputStream inputStream, OutputStream outputStream) {
        // Open the source PDF document
        Document pdfDocument = new Document(inputStream);
        // Save the file into Microsoft document format
        pdfDocument.save(outputStream, SaveFormat.Doc);
    }

    /**
     * Description:  转换pdf到word(docx)<br/>
     * Version V1.0  2020-3-31 15:58  by 秦涛   (qintao@cloud-young.com) 创建
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public static void convertPDFToDocx(InputStream inputStream, OutputStream outputStream) {
        // Load source PDF file
        Document doc = new Document(inputStream);
        // Instantiate Doc SaveOptions instance
        DocSaveOptions saveOptions = new DocSaveOptions();
        // Set output file format as DOCX
        saveOptions.setFormat(DocSaveOptions.DocFormat.DocX);
        // Save resultant DOCX file
        doc.save(outputStream, saveOptions);
    }

    /**
     * Description:  转换pdf到pptx<br/>
     * Version V1.0  2020-3-31 16:18  by 秦涛   (qintao@cloud-young.com) 创建
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public static void convertPDFToPPTX(InputStream inputStream, OutputStream outputStream) {
        // Load source PDF file
        Document doc = new Document(inputStream);
        // Instantiate PptxSaveOptions instance
        PptxSaveOptions pptx_save = new PptxSaveOptions();
        // Save the output in PPTX format
        doc.save(outputStream, pptx_save);
    }

    /**
     * Description:  转换pdf到pptx<br/>
     * Version V1.0  2020-3-31 16:18  by 秦涛   (qintao@cloud-young.com) 创建
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public static void convertPDFtoXLS(InputStream inputStream, OutputStream outputStream) {
        // Load source PDF file
        Document doc = new Document(inputStream);
        // Initialize ExcelSaveOptions
        ExcelSaveOptions options = new ExcelSaveOptions();
        // Save output file
        doc.save(outputStream, options);
    }

    public static void convertPDFToHTMLAllResourceEmbeddedInSingleResultantStream(InputStream inputStream, final OutputStream outputStream) {
        Document doc = new Document(inputStream);
        // tune conversion parameters
        HtmlSaveOptions newOptions = new HtmlSaveOptions();
        newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
        newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
        newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml;
        newOptions.LettersPositioningMethod = LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
        // force write HTMLs of all pages into one output document
        newOptions.setSplitIntoPages(false);
        newOptions.CustomHtmlSavingStrategy = new HtmlSaveOptions.HtmlPageMarkupSavingStrategy() {
            @Override
            public void invoke(HtmlSaveOptions.HtmlPageMarkupSavingInfo htmlSavingInfo) {
                try {
                    // TODO Auto-generated method stub
                    byte[] resultHtmlAsBytes = new byte[(int) htmlSavingInfo.ContentStream.available()];
                    htmlSavingInfo.ContentStream.read(resultHtmlAsBytes, 0, resultHtmlAsBytes.length);
                    // here You can use any writable stream, file stream is taken just as example
                    outputStream.write(resultHtmlAsBytes);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
        // we can use some non-existing file name all real saving will be done in CustomerHtmlSavingStrategy
        String outHtmlFile = "SomeUnexistingFile.html";
        doc.save(outputStream, newOptions);
    }


    public static void convertPDFAllPagesToJPEGImages(InputStream inputStream) throws Exception {
        // Open document
        Document pdfDocument = new Document(inputStream);
        // Loop through all the pages of PDF file
        for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) {
            // Create stream object to save the output image
            OutputStream imageStream = new java.io.FileOutputStream("Converted_Image" + pageCount + ".jpg");
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create JpegDevice object where second argument indicates the quality of resultant image
            JpegDevice jpegDevice = new JpegDevice(resolution, 100);
            // Convert a particular page and save the image to stream
            jpegDevice.process(pdfDocument.getPages().get_Item(pageCount), imageStream);
            // Close the stream
            imageStream.close();
        }
    }

    public static void convertPDFAllPDFPagesToPNGImages(InputStream inputStream) throws Exception {
        // Open document
        Document pdfDocument = new Document(inputStream);
        // Loop through all the pages of PDF file
        for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) {
            // Create stream object to save the output image
            OutputStream imageStream = new java.io.FileOutputStream("Converted_Image" + pageCount + ".png");
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create PngDevice object with particular resolution
            PngDevice pngDevice = new PngDevice(resolution);
            // Convert a particular page and save the image to stream
            pngDevice.process(pdfDocument.getPages().get_Item(pageCount), imageStream);
            // Close the stream
            imageStream.close();
        }
    }

    /**
     * Description:  提取图片<br/>
     * Version V1.0  2020-3-31 17:10  by 秦涛   (qintao@cloud-young.com) 创建
     * @throws Exception
     */
    public static void extractImagesFromThePDFFile() throws Exception {
        // Open document
        Document pdfDocument = new Document("input.pdf");
        // Loop through all the pages of PDF file
        for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) {
            // Create stream object to save the output image
            OutputStream imageStream = new java.io.FileOutputStream("Converted_Image" + pageCount + ".png");
            // Create Resolution object
            Resolution resolution = new Resolution(300);
            // Create PngDevice object with particular resolution
            PngDevice pngDevice = new PngDevice(resolution);
            // Convert a particular page and save the image to stream
            pngDevice.process(pdfDocument.getPages().get_Item(pageCount), imageStream);
            // Close the stream
            imageStream.close();
            XImageCollection images = pdfDocument.getPages().get_Item(pageCount).getResources().getImages();
            for (int i = 1; i < images.size(); i++) {
                // Extract a particular image
                XImage xImage = pdfDocument.getPages().get_Item(pageCount).getResources().getImages().get_Item(i);
                // Create stream object to save the output image
                OutputStream output = new java.io.FileOutputStream("Converted_Image" + i + ".jpg");
                // Save the output image
                xImage.save(output);
                output.close();
            }

        }
    }

    public static void convertWordToPDF() throws Exception {
        Document pdfDocument = new Document("input.pdf");

    }
    public static void concatenatePdfFiles() throws Exception {
        // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-Java
        // Open the target document
        Document pdfDocument1 = new Document("input1.pdf");

        // Open the source document
        Document pdfDocument2 = new Document("input2.pdf");

        // Add the pages of the source document to the target document
        pdfDocument1.getPages().add(pdfDocument2.getPages());

        // Save the concatenated output file (the target document)
        pdfDocument1.save("Concatenate_output.pdf");

    }


    public static void splitPDFToIndividualPages() throws Exception {
        // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-Java
        // Open a document
        Document pdfDocument1 = new Document("input.pdf");

        // Loop through the pages
        for (int pdfPage = 1; pdfPage <= pdfDocument1.getPages().size(); pdfPage++) {
            // Create a new Document object
            Document newDocument = new Document();
            // Get the page at a given index of the Page Collection
            newDocument.getPages().add(pdfDocument1.getPages().get_Item(pdfPage));
            // Save the new PDF file
            newDocument.save("page_" + pdfPage + ".pdf");
        }

    }

}
